package com.ruoyi.publish.service.impl;

import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.List;

import com.ruoyi.common.annotation.ExcelField;
import com.ruoyi.common.annotation.ExcelImportAdvice;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtilTool;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.publish.domain.ApprovalRecord;
import com.ruoyi.publish.domain.AssistInfo;
import com.ruoyi.publish.domain.SelfIncreasing;
import com.ruoyi.publish.mapper.ApprovalRecordMapper;
import com.ruoyi.publish.service.IIdIdentsampleService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.publish.mapper.IdAcceptRegisterMapper;
import com.ruoyi.publish.domain.IdAcceptRegister;
import com.ruoyi.publish.service.IIdAcceptRegisterService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 鉴定受理登记Service业务层处理
 *
 * @author confusefox
 * @date 2020-11-04
 */
@Service
public class IdAcceptRegisterServiceImpl implements IIdAcceptRegisterService {
    private static final Logger log = LoggerFactory.getLogger(IdAcceptRegisterServiceImpl.class);

    @Autowired
    private IdAcceptRegisterMapper idAcceptRegisterMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IIdIdentsampleService idIdentsampleService;

    @Autowired
    private ApprovalRecordMapper approvalRecordMapper;

    /**
     * 查询鉴定受理登记
     *
     * @param id 鉴定受理登记ID
     * @return 鉴定受理登记
     */
    @Override
    public IdAcceptRegister selectIdAcceptRegisterById(Long id) {
        return idAcceptRegisterMapper.selectIdAcceptRegisterById(id);
    }

    /**
     * 查询鉴定受理登记列表
     *
     * @param idAcceptRegister 鉴定受理登记
     * @return 鉴定受理登记
     */
    @Override
    public List<IdAcceptRegister> selectIdAcceptRegisterList(IdAcceptRegister idAcceptRegister) {
        return idAcceptRegisterMapper.selectIdAcceptRegisterList(idAcceptRegister);
    }

    /**
     * 新增鉴定受理登记
     *
     * @param idAcceptRegister 鉴定受理登记
     * @return 结果
     */
    @Override
    public int insertIdAcceptRegister(IdAcceptRegister idAcceptRegister) {
        idAcceptRegister.setCreateTime(DateUtils.getNowDate());
        if (StringUtils.isEmpty(String.valueOf(idAcceptRegister.getSampleNum()))) {
            idAcceptRegister.setSampleNum(0);

        }
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        if (StringUtils.isNotEmpty(idAcceptRegister.getEx2())) {
            year = Integer.parseInt(idAcceptRegister.getEx2());
        }
        String ex1 = null;
        SelfIncreasing selfIncreasing = idAcceptRegisterMapper.findByYear(year);
        /*自增数拼接*/
        if (selfIncreasing == null) {
            selfIncreasing = new SelfIncreasing();
            ex1 = String.valueOf(year + "-001");
            selfIncreasing.setNum(1);
            selfIncreasing.setYear(year);
            idAcceptRegisterMapper.insertSelfIncreasing(selfIncreasing);
        } else {
            int num = idAcceptRegisterMapper.findByYear(year).getNum() + 1;
            ex1 = String.valueOf(year + "-" + StringUtilTool.numberSupplement(String.valueOf(num), 3));
            selfIncreasing.setNum(num);
            selfIncreasing.setYear(year);
            idAcceptRegisterMapper.updateSelfIncreasing(selfIncreasing);
        }
//        if (StringUtils.isEmpty(idAcceptRegister.getEx1())) {
        idAcceptRegister.setEx1(ex1);
        idAcceptRegister.setEx2(String.valueOf(year));

//        }
        // 启用状态 默认为 1 启用
        if (StringUtils.isEmpty(idAcceptRegister.getIsUse())) {
            idAcceptRegister.setIsUse("1");
        }
        return idAcceptRegisterMapper.insertIdAcceptRegister(idAcceptRegister);
    }

    /**
     * 修改鉴定受理登记
     *
     * @param idAcceptRegister 鉴定受理登记
     * @return 结果
     */
    @Override
    public int updateIdAcceptRegister(IdAcceptRegister idAcceptRegister) {
        idAcceptRegister.setUpdateTime(DateUtils.getNowDate());
        return idAcceptRegisterMapper.updateIdAcceptRegister(idAcceptRegister);
    }

    /**
     * 删除鉴定受理登记对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteIdAcceptRegisterByIds(String ids) {
        return idAcceptRegisterMapper.deleteIdAcceptRegisterByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除鉴定受理登记信息
     *
     * @param id 鉴定受理登记ID
     * @return 结果
     */
    @Override
    public int deleteIdAcceptRegisterById(Long id) {
        return idAcceptRegisterMapper.deleteIdAcceptRegisterById(id);
    }

    /**
     * 是否启用状态修改
     *
     * @param idAcceptRegister 鉴定受理登记
     * @return 结果
     */
    @Override
    public int changeStatus(IdAcceptRegister idAcceptRegister) {
        return idAcceptRegisterMapper.updateIdAcceptRegister(idAcceptRegister);
    }

    /**
     * 指定业务异常回滚
     *
     * @param idAcceptRegisterList 用户数据列表
     * @param isUpdateSupport      是否更新支持，如果已存在，则进行更新数据
     * @param operId
     * @param operName             操作用户
     * @param year
     * @return
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public String importIdAcceptRegister(List<IdAcceptRegister> idAcceptRegisterList, Boolean isUpdateSupport, String operId, String operName, String year) {
        if (StringUtils.isNull(idAcceptRegisterList) || idAcceptRegisterList.size() == 0) {
            throw new BusinessException("导入案件数据不能为空！");
        }
        String yearNum = DateUtils.dateTimeNow("YYYY");
        int successNum = 0;
        int failureNum = 0;
        int reSetNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        int orderNum = 0;
        String codeNum = idAcceptRegisterMapper.getRegisterCodeBefore(year);
        for (IdAcceptRegister entity : idAcceptRegisterList) {
            orderNum++;

            if (StringUtils.isEmpty(entity.getSendUnit())) {
                continue;
            }
            try {

                //保存记录
                entity.setCreateTime(DateUtils.getNowDate());
//                entity.setAcceptDate(DateUtils.getNowDate());

                entity.setCreateBy(operId);
                entity.setCreateName(operName);
                entity.setIsUse("1");//启用
//                entity.setEx1(year + "-" + String.valueOf(Integer.parseInt(codeNum) + successNum));
                entity.setEx2(year);

                //判断审核组长 是否为空 为空 审核通过、不为空 判断系统是否存在是否为 鉴定组长 不是设置鉴定组长状态待审核 修改鉴定组长后才能进行审核
                //entity.setAuditStatus("5");//审核通过
                entity.setAuditStatus("3");
//                if (StringUtils.isEmpty(entity.getGroupLeader())) {
//                    entity.setAuditStatus("5");//审核通过
//
//                } else {
//                    SysUser user = userService.selectUserByLoginName(entity.getGroupLeader());
//                    if (user == null || StringUtils.isEmpty(user.getLoginName())) {
//                        entity.setGroupLeader("");
//                        entity.setAuditStatus("3");//审核不通过
//
//                        reSetNum++;
//                    } else {
//                        entity.setAuditStatus("3");//审核不通过
//
//                        entity.setGroupId(user.getUserId());
//                        entity.setGroupLeader(user.getUserName());
//                    }
//
//
//                }
//                entity.setEx1(idAcceptRegisterMapper.getRegisterCode());
//                int  u=idAcceptRegisterMapper.insertIdAcceptRegister(entity);
                int u = insertIdAcceptRegister(entity);


                // 验证是否保成功
                if (u == 1) {

                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 导入成功");
                } else {
                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getLoginName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + " 导入失败：";
                failureMsg.append("系统异常错误!");
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            // String resString = "未在系统中找到相应的审核组长请之后设置鉴定组长！g共" + reSetNum + "条,";
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
        }
        return successMsg.toString();
    }

    @Override
    public int ApprovalRecordRefreshByRecordId(Long id) {
        return idAcceptRegisterMapper.ApprovalRecordRefreshByRecordId(id);
    }

    /**
     * 审核受理登记
     *
     * @param idAcceptRegister
     * @return
     */
    @Transactional
    @Override
    public int handleApproval(String handleUser, String handleUserName, IdAcceptRegister idAcceptRegister) {
        int result = 0;

        if (idAcceptRegister != null && StringUtils.isNotEmpty(idAcceptRegister.getAuditStatus())) {
            int status = Integer.valueOf(idAcceptRegister.getAuditStatus());
            /**
             * 鉴定报告审批日志记录信息
             */
            ApprovalRecord recordLog = new ApprovalRecord();
            // 鉴定报告id
            recordLog.setRecordId(idAcceptRegister.getId());
            // 操作人
            recordLog.setApprovalUser(Long.valueOf(handleUser));
            recordLog.setApprovalUserName(handleUserName);
            // 审批原因
            recordLog.setApprovalReason(idAcceptRegister.getApprovalReason());
            recordLog.setSystemModule(2);
            recordLog.setApprovalType(0);
            // 通过
            if (status == 5) {
                recordLog.setApprovalStatus(1);
                // 设置已经审批
                idAcceptRegister.setAlreadyApprovalUser(handleUser);
                recordLog.setApprovalTitle("审批通过");
            } else if (status == 1) {
                // 不通过,清空鉴定组长
                idAcceptRegister.setAlreadyApprovalUser("");
                recordLog.setApprovalStatus(2);
                recordLog.setApprovalTitle("审批不通过");
            }
            addTaskApprovalLog(recordLog);
            result = idAcceptRegisterMapper.updateIdAcceptRegister(idAcceptRegister);
        }
        return result;
    }

    /**
     * 审批日志记录
     */
    private void addTaskApprovalLog(ApprovalRecord recordLog) {

        // 审批时间
        recordLog.setApprovalTime(DateUtils.getNowDate());

        recordLog.setCreateTime(DateUtils.getNowDate());

        approvalRecordMapper.insertApprovalRecord(recordLog);
    }

    @Override
    public String selectTopNewGroupId() {
        return idAcceptRegisterMapper.selectTopNewGroupId();
    }

    @Override
    public List<IdAcceptRegister> selectRecordByIds(String[] ids) {
        return idAcceptRegisterMapper.selectRecordByIds(ids);
    }

    @Override
    public AssistInfo findAssistInfo(String sampleIds,String assistType) {
        return idAcceptRegisterMapper.findAssistInfo(sampleIds,assistType);
    }

    @Override
    public int insertAssistInfo(AssistInfo assistInfo) {
        return idAcceptRegisterMapper.insertAssistInfo(assistInfo);
    }

    @Override
    public int updateAssistInfo(AssistInfo assistInfo) {
        return idAcceptRegisterMapper.updateAssistInfo(assistInfo);
    }

    @Override
    public AssistInfo queryAssist(String id) {
        return idAcceptRegisterMapper.queryAssist(id);
    }

}
